package com.zitangkou.user.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

/**
 * 远程调用工具类
 *
 * @author Deng Ningning
 * @version 1.0
 * @date 2020/8/17 11:58
 */
@Component
public class RestTemplateUtil {

    private final RestTemplate restTemplate;

    @Autowired
    public RestTemplateUtil(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public <T> T doRestTemplate(String url, HttpMethod httpMethod
            , HttpHeaders headers, Object params, Class<T> c) {
        HttpEntity<Object> requestEntity = new HttpEntity<>(params, headers);
        ResponseEntity<T> response = restTemplate.exchange(url, httpMethod
                , requestEntity, c);
        return response.getBody();
    }

    public <T> T doRestTemplateFile(String url, MediaType mediaType
            , Object params, Class<T> c) {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(mediaType);
        return doRestTemplate(url, HttpMethod.POST, httpHeaders, params, c);
    }

    public <T> T doRestTemplateT(String url, HttpMethod httpMethod
            , HttpHeaders headers
            , Object params, ParameterizedTypeReference p) {
        HttpEntity<Object> requestEntity = new HttpEntity<>(params, headers);
        ResponseEntity<T> response = restTemplate.exchange(url, httpMethod
                , requestEntity, p);
        return response.getBody();
    }

    public <T> T doRestTemplatePostJson(String url, Object params, Class<T> c) {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        return doRestTemplate(url, HttpMethod.POST, httpHeaders, params, c);
    }

    public <T> T doRestTemplatePostJsonT(String url, Object params
            , ParameterizedTypeReference p) {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        return doRestTemplateT(url, HttpMethod.POST, httpHeaders, params, p);
    }

    public <T> T doRestTemplateGet(String url, Class<T> c) {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        return doRestTemplate(url, HttpMethod.GET, httpHeaders, null, c);
    }

}
